I have two tables, OldCustomers and NewCustomers, and I need to find records that are present in
OldCustomers but not in NewCustomers. How can I write this query?
home / developersection / forums / help with writing a query to compare two tables in sql server
I have two tables, OldCustomers and NewCustomers, and I need to find records that are present in
OldCustomers but not in NewCustomers. How can I write this query?
Ravi Vishwakarma
16-Jul-2024To find records that are present in the
OldCustomerstable but not in theNewCustomerstable, you can use aLEFT JOINcombined with aWHEREclause to identify records inOldCustomersthat do not have corresponding records inNewCustomers.Here’s a general query for this scenario:
In this query:
ois an alias forOldCustomers.nis an alias forNewCustomers.LEFT JOINensures that all records fromOldCustomersare included, even if there is no matching record inNewCustomers.WHERE n.CustomerID IS NULLclause filters out records that have matches inNewCustomers, leaving only those that do not.If your tables have multiple columns that need to be checked for matching (e.g.,
CustomerID,Name,Email), you can adjust theONclause accordingly:This ensures that a record is considered a match only if all specified columns match. Adjust the column names as necessary based on the structure of your tables.